package com.cyou.gamehistory.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cyou.annals.bean.GameInfo;
import com.cyou.framework.cache.memcached.SpyMemcachedClient;
import com.cyou.framework.pagination.proxy.PaginationSupport;
import com.cyou.gamehistory.entity.Game;
import com.cyou.gamehistory.repository.GameDao;

/**
 * 游戏信息业务
 * 
 * @author wangzhang
 */
@Component
@Transactional(readOnly = true)
public class GameService {

	private static final int PAGE_SIZE = 30;

	@Autowired
	private GameDao gameDao;

	@Autowired
	private SpyMemcachedClient spyMemcachedClient;

	static final Logger logger = LoggerFactory.getLogger(GameService.class);

	/**
	 * 获取所有游戏 （本地）
	 * 
	 * @return
	 */
	public List<Game> getAllGameInfos() {
		return gameDao.getAllGameInfos();
	}

	/**
	 * 通过索引字母获取分页PaginationSupport
	 * 
	 * @param initial
	 *            索引字母
	 * @param page
	 *            当前页
	 * @return
	 */
	public PaginationSupport<Game> getGamesByInitial(String initial, int page) {

		String key = "gameListKey." + initial + "." + String.valueOf(page);
		PaginationSupport<Game> paginationGameList = spyMemcachedClient
				.get(key);
		if (paginationGameList == null) {
			Map<String, Object> map = new HashMap<String, Object>();

			PaginationSupport<Game> paginationSupport = new PaginationSupport<Game>();
			paginationSupport.setCurrentPage(page);
			paginationSupport.setPageSize(PAGE_SIZE);

			map.put("page", paginationSupport);
			map.put("initial", initial);
			paginationGameList = gameDao.findAllGamesByInitial(map);
			spyMemcachedClient.set(key, 60 * 60 * 24, paginationGameList);
		}

		return paginationGameList;
	}

	/**
	 * 通过 游戏name 或 游戏 pinyin 获取游戏list
	 * 
	 * @param condition
	 *            -------查询条件 name或pinyin
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Game> search(String condition) {
		Map map = new HashMap();
		map.put("condition", condition);
		return gameDao.search(map);
	}

	/**
	 * 定时获取游戏信息 ， 保存到自己的游戏库中
	 * 
	 * @param gameInfoList
	 *            线上游戏数据LIST
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void saveGameInfoBatch(List<GameInfo> gameInfoList) {
		logger.info("saveGame begin  gameInfoList====" + gameInfoList);
		List<Game> gameList = new ArrayList<Game>();
		
		logger.info("gameCodeSet begin");
		Set<String> gameCodeSet = this.getGameCodeSet();
		logger.info("gameCodeSet end");
		if (gameInfoList != null && gameInfoList.size() > 0) {
			logger.info("gameInfoList foreach begin");
			for (GameInfo gameInfo : gameInfoList) {
				// 判断当前游戏是否已存在 如果存在 则跳过 不存在，则保存的本地库
				String gameCode = gameInfo.getGame_code();
				if (!gameCodeSet.contains(gameCode)) {
					Game game = new Game();
					// /publisTime 未指定
					game.setAlias(gameInfo.getAlias());
					game.setBigImagePath(gameInfo.getShow_pic());
					game.setSmallImagePath(gameInfo.getLogo_pic());
					// game.setCreateTime(new
					// Date(gameInfo.getFirstTestTime()));
					game.setGameCode(gameInfo.getGame_code());
					// game.setImageTitle(gameInfo.getImageTitle());
					game.setInitial(gameInfo.getInitial());
					// game.setIntroduction(gameInfo.getIntroduction());
					game.setName(gameInfo.getName());
					game.setPinyin(gameInfo.getPinyin());
					// game.setRecommend(gameInfo.getRecommend()); 是否推荐 类型不统一···
					// game.setStatus(gameInfo.getStatus()) 状态 类型不统一
					game.setTags(gameInfo.getTags());
					gameList.add(game);
				} else {
					continue;
				}
			}
			logger.info("gameInfoList foreach end");
		}
		if (gameList != null && gameList.size() > 0) {
			logger.info("SUBLIST   begin");
			//每次同步游戏条数
			int commitCount = 100;
			//一共需要同步的游戏数
			int totalcount = gameList.size();
			//子list 的 数量    初始为0
			int subListCount = 0;
			int m = totalcount % commitCount;
			if (m > 0) {
				subListCount = totalcount / commitCount + 1;
			} else {
				subListCount = totalcount / commitCount;
			}
			for (int i = 1; i <= subListCount; i++) {
				List<Game> subList=null;
				if (m == 0) {
					subList = gameList.subList((i - 1) * commitCount, commitCount * (i));
				} else {
					if (i == subListCount) {
						subList = gameList.subList((i - 1)* commitCount, totalcount);
					} else {
						subList = gameList.subList((i - 1)* commitCount, commitCount * (i));
					}
				}
				this.synchronizeGame(subList);
			}
			logger.info("SUBLIST   end");
		}
		
		logger.info("gameDao.saveGameBatch(gameList);  end   【success】");
	}

	/**
	 * 通过游戏编号获取游戏bean
	 * 
	 * @param gameCode
	 * @return
	 */
	public Game getGameByGameCode(String gameCode) {
		return gameDao.getGameInfoByCode(gameCode);
	}

	/**
	 * 获取本地游戏 gamecodeSet
	 * 
	 * @return
	 */
	public Set<String> getGameCodeSet() {
		return gameDao.getGameCodeSet();
	}
	/**
	 * 同步游戏数据
	 * @param gameList
	 */
	@Transactional
	public void synchronizeGame(List<Game> gameList){
		gameDao.saveGameBatch(gameList);
	}

	public Integer getTotalCount() {
		return gameDao.getTotalCount();
	}

}
